/**
 * xUtils 常用方法集
 * author: imlzw
 * url: adai.imlzw.cn
 *
 */

layui.define(['jquery'], function (exports) {
        var $ = layui.jquery;
        let resources = [];
        let XUtils = function () {
            this.v = '1.0.0';
            this.renderIns = {};
        }


        /**
         * 动态加载js文件
         * @param url
         * @param callback
         */
        XUtils.prototype.loadJS = function (url, callback) {
            if (this.isLoaded(url)) {
                callback && callback();
                return;
            }
            var script = document.createElement('script'),
                fn = callback || function () {
                };
            script.type = 'text/javascript';
            //IE
            if (script.readyState) {
                script.onreadystatechange = function () {
                    if (script.readyState == 'loaded' || script.readyState == 'complete') {
                        resources.push(url);
                        script.onreadystatechange = null;
                        fn();
                    }
                };
            } else {
                //其他浏览器
                script.onload = function () {
                    resources.push(url);
                    fn();
                };
            }
            script.src = url;
            document.getElementsByTagName('head')[0].appendChild(script);
        }

        /**
         * 加载css文件
         * @param url
         */
        XUtils.prototype.loadCss = function (url, callback) {
            if (!url || url.length === 0) {
                throw new Error('argument "url" is required !');
            }
            if (this.isLoaded(url)) {
                callback && callback();
                return;
            }
            var head = document.getElementsByTagName('head')[0];
            var link = document.createElement('link');
            link.href = url;
            link.rel = 'stylesheet';
            link.type = 'text/css';
            link.onload = function () {
                resources.push(url);
                if (callback != null) {
                    callback();
                }
            };
            head.appendChild(link);
        }

        /**
         * 判断是否加载过资源了
         * @param url
         * @returns {boolean}
         */
        XUtils.prototype.isLoaded = function (url) {
            if (url) {
                for (let urlResource of resources) {
                    if (url == urlResource) {
                        return true;
                    }

                }
            }
            return false;
        }

        exports('xUtils', new XUtils());
    }
);